<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


/**
 * 用户文件模型
 * @author Cavlin
 *
 */
class User_files_model extends MY_Model {


	function __construct()
	{
		parent::__construct();
	}

	//获取最后插入id
	public function get_insert_id()
	{
		return $this->db->insert_id();
	}

	/**
	 *
	 * 获取用户文件夹列表
	 * @param $uid 用户id
	 * @param int $pid 文件夹父级id
	 * @param string $keyword 关键字
	 * @param array $conditions 其他筛选条件
	 * @param string $sort 排序字段
	 * @param string $desc 排序类型 asc升序 desc降序
	 * @param string $fields 获取的字段
	 * @param string|array $limit 获取的条数
	 * @return array|null
	 */
	public function get_folder_list($uid,$pid=0,$keyword="",$conditions=array(),$sort="name",$desc="asc",$fields="",$limit=false)
	{
		if(empty($uid))
		{
			return null;
		}
		//默认字段
		if(empty($fields)){
			$fields="id,name,creation_ts,modify_ts,access_denied";
		}
		//检查排序字段
		if(empty($sort) || $sort=="name" || !in_array($sort,array("name","creation_ts","modify_ts")))
		{
			$sort="convert(folder.name USING gbk) COLLATE gbk_chinese_ci";
		}
		else
		{
			$sort = "folder.".$sort;
		}
		//用户的文件
		$this->db->where("folder.uid",$uid);
		//所属文件夹
		if($pid!==false)
		{
			$this->db->where("folder.pid",$pid);
		}
		//其他条件
		if(!empty($conditions))
		{
			//$conditions = Common::array_key_fill($conditions,"folder.");
			//$this->db->where($conditions);
			foreach($conditions as $k=>$v)
			{
				if(is_array($v))
				{
					$this->db->where_in("folder.".$k,$v);
				}
				else
				{
					$this->db->where("folder.".$k,$v);
				}
			}
		}
		//关键字查询
		if(!empty($keyword))
		{
			$this->db->like("folder.name",$keyword);
		}
		if(!is_array($fields))
		{
			$fields = explode(",",$fields);
		}
		$select_fields=array();
		$has_children=false;
		foreach($fields as $v)
		{
			if($v=="has_children")
			{
				$select_fields[]="count(child.id) AS has_children";
				$has_children=true;
			}
			else
			{
				$select_fields[]="folder.".$v;
			}
		}

		//查询结果数组集
		$this->db
			//查询字段
			->select($select_fields)
			//查询用户文件表
			->from(self::TB_USER_FOLDERS." folder")
			//排序
			->order_by($sort,$desc)
			->group_by("folder.id");
		if($has_children)
		{
			$this->db->join(self::TB_USER_FOLDERS." child","child.pid=folder.id AND child.deleted=folder.deleted","LEFT");
		}
		if($limit!==false && $limit!=='')
		{
			$limit_arr = !is_array($limit)?explode(",",$limit):$limit;
			isset($limit_arr[1])?$this->db->limit($limit_arr[1],$limit_arr[0]):$this->db->limit($limit_arr[0]);
		}
		$rows=$this->db->get()->result_array();
		//var_dump($rows);exit;
		if(!empty($rows))
		{
			return array(
				"rows"=>$rows,
				"total"=>count($rows)
			);
		}
		else
		{
			return null;
		}
	}

	private function parse_where($where,$prefix="")
	{
		foreach($where as $k=>$v)
		{
			preg_match('/\<|\>/',$k,$find);
			$k = $prefix.$k;
			if(is_array($v))
			{
				$this->db->where_in($k,$v);
			}
			else if(!empty($find))
			{
				$this->db->where($k.$this->db->escape($v),NULL,FALSE);
			}
			else
			{
				$this->db->where($k,$v);
			}
		}
	}

	/**
	 * 检查文件夹是否存在
	 * @param $uid
	 * @param $where
	 * @return mixed
	 */
	public function check_folder_exists($uid,$where,$fields="id")
	{
		if(empty($uid) || empty($where))
		{
			return null;
		}
		//用户的文件
		$this->db->where("uid",$uid);
		$this->parse_where($where);
		$find =  $this->db->select($fields)->get_where(self::TB_USER_FOLDERS,null,1)->row_array();
		return !empty($find)?$find:false;
	}

	/**
	 * 获取文件夹的文件个数
	 * @param $uid
	 * @param $folder_id
	 * @return int
	 */
	public function get_folder_file_count($uid,$folder_id=0)
	{
		if(empty($uid))
		{
			return 0;
		}
		return $this->db->where(array("uid"=>$uid,"folder_id"=>$folder_id))->count_all_results(self::TB_USER_FILES);
	}
	/**
	 * 获取用户文件夹的具体信息
	 * @param int $uid 用户id
	 * @param int $fid 文件夹id
	 * @param bool $policy 是否包含策略
	 * @param array $folder_conditions 文件夹表的条件
	 * @param array $policy_conditions 策略表的条件
	 * @param string $folder_fields 文件夹字段
	 * @param string $policy_fields
	 * @return null
	 */
	public function get_folder_info($uid,$fid,$policy=true,$folder_conditions=array(),$policy_conditions=array(),$folder_fields="id,name,creation_ts,modify_ts,access_denied,description",$policy_fields="data")
	{
		if(empty($uid) || empty($fid))
		{
			return null;
		}
		//===================字段处理=======================
		if(!is_array($folder_fields))
		{
			$folder_fields = explode(",",$folder_fields);
		}
		if(!is_array($policy_fields))
		{
			$policy_fields = explode(",",$policy_fields);
		}
		$select_fields = array();
		foreach($folder_fields as $f_field)
		{
			$select_fields[]="folder.".$f_field;
		}
		if($policy)
		{
			foreach($policy_fields as $p_field)
			{
				$select_fields[]="policy.".$p_field;
			}
		}
		//===================字段处理=======================
		//条件处理
		$this->db->where(array("folder.uid"=>$uid,"folder.id"=>$fid));

		//其他条件
		if(!empty($folder_conditions))
		{
			$folder_conditions = Common::array_key_fill($folder_conditions,"folder.");
			$this->db->where($folder_conditions);
		}
		//其他条件
		if($policy && !empty($policy_conditions))
		{
			$policy_conditions = Common::array_key_fill($policy_conditions,"policy.");
			$this->db->where($policy_conditions);
		}
		//是否包含策略内容
		if($policy==false)
		{
			$data =$this->db
				->select($select_fields)
				->get(self::TB_USER_FOLDERS." folder",1)
				->row_array();
		}
		else
		{
			//$select_fields[]="group_concat(looker.looker_id) as lookers";
			$data =$this->db
				->select($select_fields)
				->from(self::TB_USER_FOLDERS." folder")
				->join(self::TB_USER_POLICIES." policy","policy.fid=folder.id AND policy.ftype=2 AND policy.is_global=1","LEFT")
				//->join(self::TB_USER_POLICIES_LOOKERS." looker","looker.policy_id=policy.id","LEFT")
				->get('',1)
				->row_array();
		}
		return !empty($data)?$data:null;
	}

	/**
	 * @param $uid
	 * @param $fid
	 * @return mixed
	 */
	public function get_folder_path_info($uid,$fid)
	{
		$sql = "select m.id,m.name,m.path,group_concat(p.id order by p.path asc) as path_id,group_concat(p.name order by p.path asc) as path_name from ".self::TB_USER_FOLDERS." m LEFT JOIN ".self::TB_USER_FOLDERS." p ON m.id<>p.id  AND ( m.pid=p.id OR concat(m.path, ',', m.id) LIKE CONCAT(p.path, ',', p.id, ',%') ) AND m.uid=p.uid where m.id=".$this->db->escape($fid)." AND m.uid=".$this->db->escape($uid)." GROUP BY m.id";

		return $this->db->query($sql)->row_array();
	}

	/**
	 * 获取文件夹的路径信息
	 * @param $uid
	 * @param $fids 文件夹组
	 * @param $i_field 字段
	 * @return mixed
	 */
	public function get_folders_path($uid,$i_fids,$i_field="") {

		//$tmp_field = "o.id,o.name,o.path,group_concat(o2.id order by o2.path asc) as path_id,group_concat(o2.name order by o2.path asc) as path_name";
		$tmp_field = "m.id,m.name,m.path,group_concat(p.id order by p.path asc) as path_id,group_concat(p.name order by p.path asc) as path_name";
		$i_field = empty($i_field) ? $tmp_field : $i_field.",".$tmp_field;

		if (! is_array($i_fids)) {
			$i_fids = explode(",", $i_fids);
		}

		/*
		$this->db->select($i_field);
		$this->db->join(self::TB_USER_FOLDERS." o2", " o.id<>o2.id  AND (o.pid=o2.id OR CONCAT(o.path, ',', o.id) LIKE CONCAT(o2.path, ',', o2.id, ',%')) AND o.uid=o2.uid", "LEFT", true);
		$this->db->where("o.uid", $uid);

		if (count($i_fids) == 1) {
			$this->db->where("o.id", $i_fids[0]);
		} else {
			$this->db->where_in("o.id", implode(',',$i_fids));
		}
		$this->db->group_by("o.id");

		$query = $this->db->from(self::TB_USER_FOLDERS." o")->get();
		*/

		$where_fid = " m.id";
		if (count($i_fids) == 1) {
			$where_fid .= " = ".$i_fids[0];
		} else {
			$where_fid .= " in (".implode(',',$i_fids).")";
		}

		$sql = "select ".$i_field." from ".self::TB_USER_FOLDERS." m LEFT JOIN ".self::TB_USER_FOLDERS." p ON m.id<>p.id  AND ( m.pid=p.id OR concat(m.path, ',', m.id) LIKE CONCAT(p.path, ',', p.id, ',%') ) AND m.uid=p.uid where".$where_fid." AND m.uid=".$this->db->escape($uid)." GROUP BY m.id";

		$query = $this->db->query($sql);
		$result = $query->result_array();

		return $result;
	}

	public function get_folder_path($i_fids,$folder_field="*") {

		if (! is_array($i_fids)) {
			$i_fids = explode(',', $i_fids);
		}

		if (count($i_fids) == 1) {
			$this->db->where('id', $i_fids[0]);
		} else {
			$this->db->where_in('id', $i_fids);
		}

		$result = $this->db->from(self::TB_USER_FOLDERS)->select($folder_field)->get()->result_array();

		return $result;
	}

	public function get_file_data($owner,$fids,$file_field="", $folder_field="") {
		if (empty($owner) || empty($fids)) return;

		if (! is_array($fids)) {
			$fids = explode(',', $fids);
		}

		$this->db->where('file.uid', $owner);
		if (count($fids) == 1) {
			$this->db->where('file.id', $fids[0]);
		} else {
			$this->db->where_in('file.id', $fids);
		}

		$select_fields = array();

		if (! empty($folder_field))
			$this->parse_fields($select_fields, $folder_field, "folder.");

		if (! empty($file_field))
			$this->parse_fields($select_fields, $file_field, "file.");

		if (! empty($select_fields))
			$this->db->select($select_fields);

		if (! empty($folder_field))
			$this->db->join(self::TB_USER_FOLDERS." folder", "folder.id = file.folder_id", "LEFT");

		$result = $this->db->from(self::TB_USER_FILES." file")->get()->result_array();

		return $result;
	}

	/**
	 * 获取文件夹下面文件的大小
	 * @param $uid
	 * @param $ids
	 * @return null
	 */
	public function get_folders_size($uid,$ids)
	{
		if(empty($ids) || empty($uid))
		{
			return null;
		}

		if(!is_array($ids))
		{
			$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id = '.$this->db->escape($ids).' ';
		}
		else if(is_array($ids) && count($ids)==1)
		{
			$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id = '.$this->db->escape($ids[0]).' ';
		}
		else
		{
			$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id in ('.implode(",",$ids).') ';
		}

		$ret = $this->db->query('select SUM(f.size) AS `size` FROM u_folders fd1 LEFT JOIN u_folders fd2 ON fd2.uid = fd1.uid AND fd2.deleted=fd1.deleted AND concat(fd2.path, ",", fd2.id) LIKE concat(fd1.path, ",", fd1.id, "%") LEFT JOIN u_files f ON f.uid = fd2.uid AND f.folder_id = fd2.id AND f.deleted = fd2.deleted  WHERE '.$where)->row_array();
		if(!empty($ret))
		{
			return (int)$ret['size'];
		}
		else
		{
			return 0;
		}
	}

	private function parse_fields(&$select_fields,$fields,$prefix="")
	{
		if(empty($fields))
		{
			return;
		}
		if(!is_array($fields))
		{
			$fields = explode(",",$fields);
		}
		foreach($fields as $k=>$v)
		{
			$select_fields[]=$prefix.$v;
		}
	}

	/**
	 * 获取子目录\子孙目录的文件
	 * @param $owner  拥有者
	 * @param $ids  编号列表
	 * @param bool|TRUE $all  是否查找子孙目录
	 * @param string $file_field  u_files表中的字段
	 * @param string $folder_field  u_folders表的字段
	 * @param string $secure_field  secure_files表中的guid,供下载使用
	 * @param int $file_type 2.ek / 1.exe 格式
	 * @return data
	  		[{id: "33",
			access_denied: "1",
			deleted: "0",
			name: "ACR",
			folder_id: "5",
			ext_name: "jpg",
			guid: "afa0a019d7f5120c3f282dcd0e36e33f",
			path: "0,1"}]
	 */
	public function get_folder_files_path($owner,$ids,$all=true,$file_fields="",$folder_fields="",$secure_field="",$file_type=2) {
		if(empty($owner) || empty($ids) || empty($file_fields))
			return;

		$select_fields=array();
		if(!empty($file_fields))
		{
			$this->parse_fields($select_fields,$file_fields,"file.");
		}
		if (! empty($folder_fields)) {
			$this->parse_fields($select_fields,$folder_fields,"fd2.");
		}

		if (! empty($secure_field)) {
			$this->parse_fields($select_fields, $secure_field, "sec.");
		}

		$ids = is_array($ids) ? $ids : explode(',', $ids);
		//子孙目录
		if(true == $all) {
			if ($ids == 1) {
				$this->db->where('fd1.id', $ids[0]);
			} else {
				$this->db->where_in('fd1.id', $ids);
			}
			$this->db->where('fd1.uid', $owner);

			$this->db->select($select_fields)
					->from(self::TB_USER_FOLDERS." fd1")
					->join(self::TB_USER_FOLDERS." fd2", "fd2.uid = fd1.uid AND fd2.deleted=fd1.deleted AND concat(fd2.path, \",\", fd2.id) LIKE concat(fd1.path, \",\", fd1.id, \"%\")","LEFT")
					->join(self::TB_USER_FILES." file", "file.uid = fd2.uid AND file.folder_id = fd2.id AND file.deleted = fd2.deleted", "LEFT");

			if (! empty($secure_field))
				$this->db->join(self::TB_SECURE_FILES." sec", "file.id = sec.fid AND sec.type = ".$file_type, "LEFT");

			$this->db->group_by("file.id")
					->having("file.id IS NOT NULL");

			$data = $this->db->get()->result_array();
			//echo $this->db->last_query();die;
		//只查询子目录
		} else {
			if ($ids == 1) {
				$this->db->where('fd2.id', $ids[0]);
			} else {
				$this->db->where_in('fd2.id', $ids);
			}

			$this->db->where('file.uid', $owner);

			$this->db->select($select_fields)
					->from(self::TB_USER_FILES." file")
					->join(self::TB_USER_FOLDERS." fd2", "file.folder_id = fd2.id", "LEFT")
					->group_by("file.id")
					->having("file.id IS NOT NULL");

			$data = $this->db->get()->result_array();
		}

		return $data;
	}

	/**
	 * 获取文件夹下面的文件
	 * @param $uid 用户id
	 * @param $ids 文件夹的id，多个文件夹则传array(id);
	 * @param bool $all 是否查找所有子目录的文件
	 * @param string $file_fields 文件的字段
	 * @param string $policy_fields 文件夹的字段
	 * @return array|null
	 */
	public function get_folder_files($uid,$ids,$all=true,$file_fields="id",$policy_fields="",$folder_fields="")
	{
		if(empty($uid) || (empty($file_fields) && empty($policy_fields)))
		{
			return null;
		}
		$select_fields=array();
		if(!empty($file_fields))
		{
			$this->parse_fields($select_fields,$file_fields,"file.");
		}
		if(!empty($policy_fields))
		{
			$this->parse_fields($select_fields,$policy_fields,"policy.");
		}
		if (! empty($folder_fields)) {
			$this->parse_fields($select_fields,$folder_fields,"folder.");
		}

		$data = array();
		if($all)
		{
			if(!is_array($ids))
			{
				$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id = '.$this->db->escape($ids).' ';
			}
			else if(is_array($ids) && count($ids)==1)
			{
				$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id = '.$this->db->escape($ids[0]).' ';
			}
			else
			{
				$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id in ('.implode(",",$ids).') ';
			}
			$policy_join = '';
			if(!empty($policy_fields))
			{
				$policy_join = ' LEFT JOIN `'.self::TB_USER_POLICIES.'` policy ON policy.fid=file.id AND policy.ftype=1 ';
			}
			$data = $this->db->query('select '.implode(",",$select_fields).' FROM `'.self::TB_USER_FOLDERS.'` fd1 LEFT JOIN `'.self::TB_USER_FOLDERS.'` fd2 ON fd2.uid = fd1.uid AND fd2.deleted=fd1.deleted AND concat(fd2.path, ",", fd2.id) LIKE concat(fd1.path, ",", fd1.id, "%") LEFT JOIN `'.self::TB_USER_FILES.'` file ON file.uid = fd2.uid AND file.folder_id = fd2.id AND file.deleted = fd2.deleted '.$policy_join.' WHERE '.$where." GROUP BY file.id HAVING file.id IS NOT NULL")->result_array();
		}
		else
		{
			if(!is_array($ids))
			{
				$this->db->where("file.folder_id",$ids);
			}
			else if(is_array($ids) && count($ids)==1)
			{
				$this->db->where("file.folder_id",$ids[0]);
			}
			else
			{
				$this->db->where_in("file.folder_id",$ids);
			}
			$this->db->where("file.uid",$uid);
			$this->db
				->select($select_fields)
				->from(self::TB_USER_FILES." file")
				//->join(self::TB_FILE_TYPE." type","type.id=file.type","LEFT")
				->group_by("file.id")
				->having("file.id IS NOT NULL");

			if(!empty($policy_fields))
			{
				$this->db->join(self::TB_USER_POLICIES." policy","policy.fid=file.id AND policy.ftype=1","LEFT");
			}
			$data = $this->db->get()->result_array();
		}
		return $data;
	}

	/**
	 * @param $owner
	 * @param $ids
	 * @param string $where
	 * @param string $field
	 */
	public function get_multidim_folders($owner,$ids,$where="",$field="") {
		if (empty($owner) || empty($ids))
			return;

		if (empty($field)) {
			$field = "*";
		} else {
			if (! is_array($field)) {
				$field = explode(",", $field);
			}
		}

		$this->db->select($field);

		if (! empty($ids)) {
			if (! is_array($ids))
				$ids = explode(",", $ids);

			count($ids) == 1 ? $this->db->where('id', $ids[0]) : $this->db->where_in('id', $ids);
		}

		if (! empty($where)) {
			if (! is_array($where))
				$where = explode(",", $where);

			count($where) == 1 ? $this->db->where($where) : $this->db->where_in($where);
		}

		$result = $this->db->from(self::TB_USER_FOLDERS)->get()->result_array();
		return $result;
	}

	/**
	 * 获取文件夹的子目录
	 * @param $uid 用户id
	 * @param $ids 文件夹的ID
	 * @param bool $all 是否查找所以子节点
	 * @param string $folder_fields 文件夹的字段
	 * @param string $policy_fields 策略的字段
	 * @return array|null
	 */
	public function get_folder_children($uid,$ids,$all=true,$folder_fields="id",$policy_fields="")
	{
		if(empty($uid) || (empty($folder_fields) && empty($policy_fields)))
		{
			return null;
		}
		$select_fields=array();
		if(!empty($folder_fields))
		{
			$this->parse_fields($select_fields,$folder_fields,"fd2.");
		}
		if(!empty($policy_fields))
		{
			$this->parse_fields($select_fields,$policy_fields,"policy.");
		}
		$data = array();
		if($all)
		{
			if(!is_array($ids))
			{
				$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id = '.$this->db->escape($ids).' ';
			}
			else if(is_array($ids) && count($ids)==1)
			{
				$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id = '.$this->db->escape($ids[0]).' ';
			}
			else
			{
				$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id in ('.implode(",",$ids).') ';
			}
			$policy_join = '';
			if(!empty($policy_fields))
			{
				$policy_join = ' LEFT JOIN `'.self::TB_USER_POLICIES.'` policy ON policy.fid=fd2.id AND policy.ftype=2 ';
			}
			$data = $this->db->query('select '.implode(",",$select_fields).' FROM `'.self::TB_USER_FOLDERS.'` fd1 LEFT JOIN `'.self::TB_USER_FOLDERS.'` fd2 ON fd2.uid = fd1.uid AND fd2.deleted=fd1.deleted AND concat(fd2.path, ",", fd2.id) LIKE concat(fd1.path, ",", fd1.id, "%") '.$policy_join.'  WHERE '.$where." GROUP BY fd2.id")->result_array();
		}
		else
		{
			if(!is_array($ids))
			{
				$this->db->where("fd2.pid",$ids);
			}
			else if(is_array($ids) && count($ids)==1)
			{
				$this->db->where("fd2.pid",$ids[0]);
			}
			else
			{
				$this->db->where_in("fd2.pid",$ids);
			}
			$this->db->where("fd2.uid",$uid);
			$this->db
				->select($select_fields)
				->from(self::TB_USER_FOLDERS." fd2")
				->group_by("fd2.id");;

			if(!empty($policy_fields))
			{
				$this->db->join(self::TB_USER_POLICIES." policy","policy.fid=fd2.id AND policy.ftype=2","LEFT");
			}
			$data = $this->db->get()->result_array();
		}
		return $data;
	}

	/**
	 * 添加文件夹
	 * @param $uid
	 * @param $data
	 * @return mixed
	 */
	public function add_folder($uid,$data)
	{
		if(empty($uid) || empty($data))
		{
			return false;
		}
		$data['uid']=$uid;
		return $this->db->insert(self::TB_USER_FOLDERS,$data);
	}

	/**
	 * 更新文件信息
	 * @param $where 条件
	 * @param $data 修改数据
	 */
	public function update_folder($uid,$where,$data)
	{
		if(empty($uid) || empty($where) || empty($data))
		{
			return false;
		}
		if(isset($where['uid']))
		{
			unset($where['uid']);
		}
		if(!isset($data['modify_ts']))
		{
			$data['modify_ts']=time();
		}
		return $this->db->where($where)->where("uid",$uid)->update(self::TB_USER_FOLDERS, $data);
	}

	/**
	 * 文件夹及时收回状态修改
	 * @param $uid 用户id
	 * @param $ids 文件夹id
	 * @param $denied 状态值 0禁止访问 1允许访问
	 * @param $all 是否应用到所有子目录
	 */
	public function update_folder_access_denied($uid,$ids,$denied,$all=true)
	{
		if(empty($uid) || empty($ids) || !is_numeric($denied))
		{
			return false;
		}
		$time=time();
		if(!is_array($ids))
		{
			$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id = '.$this->db->escape($ids).' ';
		}
		else if(is_array($ids) && count($ids)==1)
		{
			$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id = '.$this->db->escape($ids[0]).' ';
		}
		else
		{
			$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id in ('.implode(",",$ids).') ';
		}
		if($all)
		{
			$ret =  $this->db->query('UPDATE u_folders fd1 LEFT JOIN u_folders fd2 ON fd2.uid = fd1.uid AND concat(fd2.path, ",", fd2.id) LIKE concat(fd1.path, ",", fd1.id, "%") LEFT JOIN u_files f ON f.uid = fd2.uid AND f.folder_id = fd2.id SET fd1.access_denied = '.$denied.',fd1.modify_ts='.$time.',fd2.access_denied = '.$denied.',fd2.modify_ts='.$time.',f.access_denied = '.$denied.',f.modify_ts='.$time.' WHERE '.$where);
		}
		else
		{
			$ret =  $this->db->query('UPDATE u_folders fd1 LEFT JOIN u_files f ON f.uid = fd1.uid AND f.folder_id = fd1.id SET fd1.access_denied = '.$denied.',fd1.modify_ts='.$time.',f.access_denied = '.$denied.',f.modify_ts='.$time.' WHERE '.$where);
		}
		return $ret;
	}

	/**
	 * 删除文件夹
	 * @param $uid
	 * @param $files
	 * @param $folders
	 * @param bool $real
	 */
	public function delete_folders($uid,$ids,$real=false)
	{
		if(empty($uid) || empty($ids))
		{
			return false;
		}
		if(!is_array($ids))
		{
			$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id = '.$this->db->escape($ids).' ';
		}
		else if(is_array($ids) && count($ids)==1)
		{
			$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id = '.$this->db->escape($ids[0]).' ';
		}
		else
		{
			$where = 'fd1.uid = '.$this->db->escape($uid).' AND fd1.id in ('.implode(",",$ids).') ';
		}
		$time = time();
		if($real==false)
		{
			return $this->db->query('UPDATE '.self::TB_USER_FOLDERS.' fd1 LEFT JOIN '.self::TB_USER_FOLDERS.' fd2 ON fd2.uid = fd1.uid AND concat(fd2.path, ",", fd2.id) LIKE concat(fd1.path, ",", fd1.id, "%") LEFT JOIN '.self::TB_USER_FILES.' f ON f.uid = fd2.uid AND f.folder_id = fd2.id SET fd1.deleted = 1,fd1.modify_ts='.$time.',fd1.deleted_ts='.$time.',fd2.deleted = 1,fd2.modify_ts='.$time.',fd2.deleted_ts='.$time.',f.deleted = 1,f.modify_ts='.$time.',f.deleted_ts='.$time.' WHERE '.$where);
		}
		else
		{
			return $this->db->query('DELETE fd1.*,fd2.*,f.*,p1.*,p2.*,t.* FROM '.self::TB_USER_FOLDERS.' fd1 LEFT JOIN '.self::TB_USER_FOLDERS.' fd2 ON fd2.uid = fd1.uid AND concat(fd2.path, ",", fd2.id) LIKE concat(fd1.path, ",", fd1.id, "%") LEFT JOIN '.self::TB_USER_FILES.' f ON f.uid = fd2.uid AND f.folder_id = fd2.id LEFT JOIN '.self::TB_USER_POLICIES.' p2 ON p2.fid = fd2.id AND p2.ftype=2  LEFT JOIN '.self::TB_USER_POLICIES.' p1 ON p1.fid = f.id AND p1.ftype=1 LEFT JOIN '.self::TB_FILE_TRACES.' t ON t.file_id=f.id WHERE '.$where);
		}
	}


	/**
	 *
	 * 获取用户的文件列表或者获取策略过期的文件列表
	 * @readme 由于查询过期策略必须关联策略表，所以$find_exp_policy_files参数区分两种查询
	 * @param $uid 用户id
	 * @param bool $find_exp_policy_files 是否是查找默认策略过期的文件列表
	 * @param int $folder_id 文件夹id
	 * @param string $keyword 关键字
	 * @param array $conditions 其他条件
	 * @param string $sort 排序
	 * @param string $direction asc升序 desc降序
	 * @param string $file_fields 文件表的字段
	 * @param string $ftype_fields 文件类型表的字段
	 * @param string|array $limit 获取多少行 例如：0,15则从0开始取15条
	 * @return array|null
	 */
	public function get_file_list($uid,$find_exp_policy_files=false,$folder_id=0,$keyword="",$conditions=array(),$sort="name",$direction="asc",$file_fields="",$ftype_fields="",$limit=false)
	{

		if(empty($uid))
		{
			return null;
		}

		if(empty($file_fields)){
			$file_fields = "id,name,size,creation_ts,modify_ts,access_denied,ext_name";
		}
		//var_dump($sort);die();
		//检查排序字段
		if(empty($sort) || $sort=="name" || !in_array($sort,array("name","modify_ts","size","creation_ts")))
		{
			$sort="convert(file.name USING gbk) COLLATE gbk_chinese_ci";
		}
		else
		{
			$sort = "file.".$sort;
		}
		/*if(!empty($ftype_fields) && !is_array($file_fields))
		{
			$file_fields = explode(",",$file_fields);
		}
		if(!empty($ftype_fields) && !is_array($ftype_fields))
		{
			$ftype_fields = explode(",",$ftype_fields);
		}*/
		$select_fields = array();

		$this->parse_fields($select_fields,$file_fields,"file.");
		$this->parse_fields($select_fields,$ftype_fields,"type.");
		/*if(!empty($file_fields))
		{
			foreach($file_fields as $field1)
			{
				$select_fields[]="file.".$field1;
			}
		}

		if(!empty($ftype_fields))
		{
			foreach($ftype_fields as $field2)
			{
				$select_fields[]="type.".$field2;
			}
		}*/


		//=======================策略条件处理============================
		if($find_exp_policy_files)
		{
			$time = time();
			$this->db
				->where(array(
					"policy.uid"=>$uid,
					"policy.ftype"=>1,//文件
					"policy.is_global"=>1//全局策略
				))
				->where("((policy.expiration_ts <>0 AND policy.expiration_ts<$time) OR policy.expired=1)");//时间过期或者状态过期
		}


		//=======================用户文件条件处理=========================
		//用户的文件
		$this->db->where("file.uid",$uid);
		//所属文件夹
		if($folder_id!==false)
		{
			$this->db->where("file.folder_id",$folder_id);
		}
		//其他条件
		if(!empty($conditions) && is_array($conditions))
		{
			foreach($conditions as $con_k =>$con_v)
			{
				//$other_condition['file.'.$con_k]=$con_v;
				if(is_array($con_v))
				{
					$this->db->where_in('file.'.$con_k,$con_v);
				}
				else
				{
					$this->db->where('file.'.$con_k,$con_v);
				}

			}
			/*if(!empty($other_condition))
			{

			}*/
		}
		//关键字查询
		if(!empty($keyword))
		{
			//$this->db->like("file.name",$keyword);
			$this->db->where("concat(file.name,'.',file.ext_name) like '%$keyword%'");
		}
		//=======================用户文件条件处理=========================


		//查询策略过期的文件列表
		if($find_exp_policy_files)
		{

			//查询结果数组集
			$this->db
				//查询字段
				->select($select_fields)
				//查询策略表
				->from(self::TB_USER_POLICIES." policy")
				//连接查询用户文件表
				->join(self::TB_USER_FILES." file","policy.fid=file.id","LEFT")
				//连接查询文件类型
				//->join(self::TB_FILE_TYPE." type",'file.type=type.id',"LEFT")
				//排序
				->order_by($sort,$direction)
				//针对文件的查询
				->group_by("file.id");

		}
		//普通文件列表查询
		else
		{
			//查询结果数组集
			$this->db
				//查询字段
				->select($select_fields)
				//查询用户文件表
				->from(self::TB_USER_FILES." file")
				//连接查询文件类型
				//->join(self::TB_FILE_TYPE." type",'file.type=type.id',"LEFT")
				//排序
				->order_by($sort,$direction);
		}
		if(!empty($ftype_fields))
		{
			$this->db->join(self::TB_FILE_TYPE." type",'file.type=type.id',"LEFT");
		}
		if($limit!==false && $limit!=='')
		{
			$limit_arr = !is_array($limit)?explode(",",$limit):$limit;
			isset($limit_arr[1])?$this->db->limit($limit_arr[1],$limit_arr[0]):$this->db->limit($limit_arr[0]);
		}
		//执行查询
		$rows =	$this->db->get()->result_array();
		if(!empty($rows))
		{
			return array(
				"rows"=>$rows,
				"total"=>count($rows)
			);
		}
		else
		{
			return null;
		}
	}

	/**
	 * 获取文件的具体信息
	 * @param $uid 用户id
	 * @param $fid 文件id
	 * @param bool $policy 是否包含策略
	 * @param array $file_conditions 文件表的条件
	 * @param array $policy_conditions 策略表的条件
	 * @param string $file_fields 文件表的字段
	 * @param string $policy_fields 策略表的字段
	 * @return null
	 */
	public function get_file_info($uid,$fid,$policy=false,$file_conditions=array(),$policy_conditions=array(),$file_fields="id,name,ext_name,size,creation_ts,modify_ts,access_denied,description",$policy_fields="data")
	{
		if(empty($uid) || empty($fid))
		{
			return null;
		}
		//===================字段处理=======================
		if(!is_array($file_fields))
		{
			$file_fields = explode(",",$file_fields);
		}
		if(!is_array($policy_fields))
		{
			$policy_fields = explode(",",$policy_fields);
		}
		$select_fields = array();
		foreach($file_fields as $f_field)
		{
			$select_fields[]="file.".$f_field;
		}
		if($policy)
		{
			foreach($policy_fields as $p_field)
			{
				$select_fields[]="policy.".$p_field;
			}
		}
		//===================字段处理=======================
		//条件处理
		$this->db->where(array("file.uid"=>$uid,"file.id"=>$fid));

		//其他条件
		if(!empty($file_conditions))
		{
			$file_conditions = Common::array_key_fill($file_conditions,"file.");
			$this->db->where($file_conditions);
		}
		//其他条件
		if($policy && !empty($policy_conditions))
		{
			$policy_conditions = Common::array_key_fill($policy_conditions,"policy.");
			$this->db->where($policy_conditions);
		}

		//是否包含策略内容
		if($policy==false)
		{
			$data =$this->db
				->select($select_fields)
				->get(self::TB_USER_FILES." file",1)
				->row_array();
		}
		else
		{
			$data =$this->db
				->select($select_fields)
				->from(self::TB_USER_FILES." file")
				->join(self::TB_USER_POLICIES." policy","policy.fid=file.id AND policy.ftype=1 AND policy.is_global=1","LEFT")
				->get('',1)
				->row_array();
		}
		return !empty($data)?$data:null;
	}

	public function get_files_info($uid,$fids,$policy=false,$file_conditions=array(),$policy_conditions=array(),$file_fields="id,name,size,creation_ts,modify_ts,access_denied,description",$policy_fields="data")
	{
		if(empty($uid) || empty($fids))
		{
			return null;
		}
		//===================字段处理=======================
		if(!is_array($file_fields))
		{
			$file_fields = explode(",",$file_fields);
		}
		if(!is_array($policy_fields))
		{
			$policy_fields = explode(",",$policy_fields);
		}
		$select_fields = array();
		foreach($file_fields as $f_field)
		{
			$select_fields[]="file.".$f_field;
		}
		if($policy)
		{
			foreach($policy_fields as $p_field)
			{
				$select_fields[]="policy.".$p_field;
			}
		}
		//===================字段处理=======================
		//条件处理
		$this->db->where(array("file.uid"=>$uid));
		if(is_array($fids) && count($fids)>0)
		{
			$this->db->where_in("file.id",$fids);
		}
		else if(is_array($fids) && count($fids)<=0)
		{
			$this->db->where("file.id",$fids[0]);
		}
		else
		{
			$this->db->where("file.id",$fids);
		}
		//其他条件
		if(!empty($file_conditions))
		{
			$file_conditions = Common::array_key_fill($file_conditions,"file.");
			$this->db->where($file_conditions);
		}
		//其他条件
		if($policy && !empty($policy_conditions))
		{
			$policy_conditions = Common::array_key_fill($policy_conditions,"policy.");
			$this->db->where($policy_conditions);
		}

		//是否包含策略内容
		if($policy==false)
		{
			$data =$this->db
				->select($select_fields)
				->get(self::TB_USER_FILES." file")
				->result_array();
		}
		else
		{
			$data =$this->db
				->select($select_fields)
				->from(self::TB_USER_FILES." file")
				->join(self::TB_USER_POLICIES." policy","policy.fid=file.id AND policy.ftype=1 AND policy.is_global=1","LEFT")
				->get('')
				->result_array();
		}
		return !empty($data)?$data:null;
	}

	/**
	 *
	 * 获取文件信息（不检测用户）
	 * @param $fid 文件id
	 * @param array $file_conditions 文件表的条件
	 * @param array $policy_conditions 策略表的条件
	 * @param array $secure_conditions 受控文件的条件
	 * @param string $file_fields 文件表的字段
	 * @param string $policy_fields 策略表的字段
	 * @param string $secure_fields 受控文件表的字段
	 * @return null
	 */
	public function get_all_file_info($fid,$file_conditions=array(),$policy_conditions=array(),$secure_conditions=array(),$file_fields="id,name,size,creation_ts,modify_ts,access_denied,description",$policy_fields="data",$secure_fields="cipher")
	{
		if(empty($fid))
		{
			return null;
		}
		//===================字段处理=======================
		/*if(!is_array($file_fields))
		{
			$file_fields = explode(",",$file_fields);
		}
		if(!is_array($policy_fields))
		{
			$policy_fields = explode(",",$policy_fields);
		}
		if(!is_array($secure_fields))
		{
			$secure_fields = explode(",",$secure_fields);
		}*/
		$select_fields = array();
		/*foreach($file_fields as $f_field)
		{
			$select_fields[]="file.".$f_field;
		}
		if(!empty($policy_fields))
		{
			foreach($policy_fields as $p_field)
			{
				$select_fields[]="policy.".$p_field;
			}
		}
		if(!empty($secure_fields))
		{
			foreach($secure_fields as $s_field)
			{
				$select_fields[]="sec.".$s_field;
			}
		}*/
		$this->parse_fields($select_fields,$file_fields,"file.");
		$this->parse_fields($select_fields,$policy_fields,"policy.");
		$this->parse_fields($select_fields,$secure_fields,"sec.");
		//===================字段处理=======================
		//条件处理
		$this->db->where(array("file.id"=>$fid));

		//其他条件
		if(!empty($file_conditions))
		{
			$file_conditions = Common::array_key_fill($file_conditions,"file.");
			$this->db->where($file_conditions);
		}
		//策略表的条件
		if(!empty($policy_conditions))
		{
			$policy_conditions = Common::array_key_fill($policy_conditions,"policy.");
			$this->db->where($policy_conditions);
		}

		$this->db
			->select($select_fields)
			->from(self::TB_USER_FILES." file")
			->limit(1);
		//是否包含策略内容
		if(!empty($policy_fields))
		{
			$this->db->join(self::TB_USER_POLICIES." policy","policy.fid=file.id AND policy.ftype=1 AND policy.is_global=1","LEFT");
		}
		if(!empty($secure_fields))
		{
			$sec_on = "sec.fid=file.id ";
			if(!empty($secure_conditions))
			{
				 foreach($secure_conditions as $k=>$v)
				 {
					 $sec_on .= " AND sec.".$k."=".$v;
				 }
			}
			$this->db->join(self::TB_USER_SECURE_FILES." sec",$sec_on,"LEFT");
		}
		$data=$this->db
			->group_by("file.id")
			->get()
			->row_array();
		return !empty($data)?$data:null;
	}

	/**
	 *
	 * 获取文件信息（不检测用户）
	 * @param $fid 文件id
	 * @param array $file_conditions 文件表的条件
	 * @param array $policy_conditions 策略表的条件
	 * @param array $secure_conditions 受控文件的条件
	 * @param string $file_fields 文件表的字段
	 * @param string $policy_fields 策略表的字段
	 * @param string $secure_fields 受控文件表的字段
	 * @return null
	 */
	public function get_all_file_info_by_guid($guid,$file_conditions=array(),$policy_conditions=array(),$secure_conditions=array(),$file_fields="id,name,size,creation_ts,modify_ts,access_denied,description",$policy_fields="data",$secure_fields="cipher")
	{
		if(empty($guid))
		{
			return null;
		}
		//===================字段处理=======================
		/*if(!is_array($file_fields))
		{
			$file_fields = explode(",",$file_fields);
		}
		if(!is_array($policy_fields))
		{
			$policy_fields = explode(",",$policy_fields);
		}
		if(!is_array($secure_fields))
		{
			$secure_fields = explode(",",$secure_fields);
		}*/
		$select_fields = array();
		/*foreach($file_fields as $f_field)
		{
			$select_fields[]="file.".$f_field;
		}
		if(!empty($policy_fields))
		{
			foreach($policy_fields as $p_field)
			{
				$select_fields[]="policy.".$p_field;
			}
		}
		if(!empty($secure_fields))
		{
			foreach($secure_fields as $s_field)
			{
				$select_fields[]="sec.".$s_field;
			}
		}*/
		$this->parse_fields($select_fields,$file_fields,"file.");
		$this->parse_fields($select_fields,$policy_fields,"policy.");
		$this->parse_fields($select_fields,$secure_fields,"sec.");
		//===================字段处理=======================
		//条件处理
		$this->db->where(array("file.guid"=>$guid));

		//其他条件
		if(!empty($file_conditions))
		{
			$file_conditions = Common::array_key_fill($file_conditions,"file.");
			$this->db->where($file_conditions);
		}
		//策略表的条件
		if(!empty($policy_conditions))
		{
			$policy_conditions = Common::array_key_fill($policy_conditions,"policy.");
			$this->db->where($policy_conditions);
		}

		$this->db
			->select($select_fields)
			->from(self::TB_USER_FILES." file")
			->limit(1);
		//是否包含策略内容
		if(!empty($policy_fields))
		{
			$this->db->join(self::TB_USER_POLICIES." policy","policy.fid=file.id AND policy.ftype=1 AND policy.is_global=1","LEFT");
		}
		if(!empty($secure_fields))
		{
			$sec_on = "sec.fid=file.id ";
			if(!empty($secure_conditions))
			{
				foreach($secure_conditions as $k=>$v)
				{
					$sec_on .= " AND sec.".$k."=".$v;
				}
			}
			$this->db->join(self::TB_USER_SECURE_FILES." sec",$sec_on,"LEFT");
		}
		$data=$this->db
			->group_by("file.id")
			->get()
			->row_array();
		return !empty($data)?$data:null;
	}
	/**
	 * 通过后缀名获取
	 * @param $ext_name 后缀名
	 * @param string $mime_type
	 */
	public function get_file_type($ext_name,$mime_type="",$fields="id,ext_name,group,mime_type")
	{
		$this->db->where("ext_name",$ext_name);
		if(!empty($mime_type))
		{
			$this->db->where("mime_type",$mime_type);
		}
		return $this->db->select($fields)->get_where(self::TB_FILE_TYPE,null,1)->row_array();
	}


	public function mime_type_info($mime_type,$fields="id,ext_name,group,mime_type")
	{
		if(empty($mime_type))
		{
			return null;
		}
		$this->db->where("mime_type",$mime_type);
		return $this->db->select($fields)->get_where(self::TB_FILE_TYPE,null,1)->row_array();
	}


	public function check_source_file_exists($md5,$fields="guid")
	{
		if(empty($md5))
		{
			return false;
		}
		$where=array(
			"hash"=>Common::time33($md5),
			"md5"=>$md5
		);
		$find =  $this->db->select($fields)->get_where(self::TB_SOURCE_FILES,$where,1)->row_array();
		return !empty($find)?$find:false;
	}

	/**
	 * 新增文件信息
	 * @param $data
	 * @return mixed
	 */
	public function add_file($uid,$data)
	{
		if(empty($uid) || empty($data))
		{
			return false;
		}
		$data['uid']=$uid;
		return $this->db->insert(self::TB_USER_FILES,$data);
	}

	/**
	 * 新增源文件
	 * @param $data
	 * @return mixed
	 */
	public function add_source_file($data)
	{
		if(empty($data))
		{
			return false;
		}
		return $this->db->insert(self::TB_SOURCE_FILES,$data);
	}
	/**
	 * 新增受控文件
	 * @param $data
	 * @return mixed
	 */
	public function add_secure_file($data)
	{
		if(empty($data))
		{
			return false;
		}
		return $this->db->insert(self::TB_USER_SECURE_FILES,$data);
	}
	/**
	 * 更新文件信息
	 * @param $where 条件
	 * @param $data 修改数据
	 */
	public function update_file($uid,$where,$data)
	{
		if(empty($where) || empty($data))
		{
			return false;
		}
		if(isset($where['uid']))
		{
			unset($where['uid']);
		}
		if(!isset($data['modify_ts']))
		{
			$data['modify_ts']=time();
		}
		return $this->db->where($where)->where("uid",$uid)->update(self::TB_USER_FILES, $data);
	}

	public function open_update_file($where,$data)
	{
		return $this->db->where($where)->update(self::TB_USER_FILES, $data);
	}
	public function update_files($data)
	{
		return $this->db->update_batch(self::TB_USER_FILES, $data,"id");
	}

	/**
	 * 修改用户的文件信息
	 * @param $uid 用户id
	 * @param $id 文件id
	 * @param $data 修改数据
	 * @return mixed
	 */
	public function update_file_by_id($uid,$id,$data)
	{
		if(empty($id) || empty($uid) || empty($data))
		{
			return false;
		}
		$where=array(
			"id"=>$id
		);
		return $this->update_file($uid,$where,$data);
	}

	/**
	 * 批量更新文件
	 * @param $uid
	 * @param $ids
	 * @param $data
	 */
	public function update_file_by_ids($uid,$ids,$data)
	{
		if(empty($ids) || empty($uid) || empty($data))
		{
			return false;
		}
		$this->db->where("uid",$uid);
		if(!is_array($ids))
		{
			$this->db->where("id",$ids);
		}
		else if(is_array($ids) && count($ids)==1)
		{
			$this->db->where("id",$ids[0]);
		}
		else
		{
			$this->db->where_in("id",$ids);
		}
		if(!isset($data['modify_ts']))
		{
			$data['modify_ts']=time();
		}
		return $this->db->update(self::TB_USER_FILES, $data);
	}
	/**
	 * 删除用户文件
	 * @param $uid
	 * @param $id
	 * @param bool $real
	 * @return mixed
	 */
	/*public function delete_file($uid,$id,$real=false)
	{
		if(empty($id) || empty($uid))
		{
			return null;
		}
		$where=array(
			"id" => $id,
			"uid" => $uid
		);
		$this->db->where($where);
		if($real)
		{
			return $this->db->delete(self::TB_USER_FILES);
		}
		else
		{
			return $this->db->update(self::TB_USER_FILES, array("deleted"=>1,"deleted_ts"=>time(),"modify_ts"=>time()));
		}
	}*/

	/**
	 * 批量删除用户文件
	 *
	 * @param $uid
	 * @param $ids
	 * @param bool $real
	 * @return CI_DB_active_record|null
	 */
	public function delete_files($uid,$ids,$real=false)
	{
		if(empty($ids) || empty($uid))
		{
			return false;
		}
		/*$this->db->where("uid",$uid);
		if(!is_array($ids))
		{
			$this->db->where("id",$ids);
		}
		else if(is_array($ids) && count($ids)==1)
		{
			$this->db->where("id",$ids[0]);
		}
		else
		{
			$this->db->where_in("id",$ids);
		}*/

		if(!is_array($ids))
		{
			$where = 'f1.uid = '.$this->db->escape($uid).' AND f1.id = '.$this->db->escape($ids).' ';
		}
		else if(is_array($ids) && count($ids)==1)
		{
			$where = 'f1.uid = '.$this->db->escape($uid).' AND f1.id = '.$this->db->escape($ids[0]).' ';
		}
		else
		{
			$where = 'f1.uid = '.$this->db->escape($uid).' AND f1.id in ('.implode(",",$ids).') ';
		}
		$time = time();
		if($real)
		{
			return $this->db->query('DELETE f1.*,p.*,t.* FROM '.self::TB_USER_FILES.' f1 LEFT JOIN '.self::TB_USER_POLICIES.' p ON p.fid=f1.id AND p.ftype=1 LEFT JOIN '.self::TB_FILE_TRACES.' t ON t.file_id = f1.id WHERE '.$where);
		}
		else
		{
			return $this->db->query('UPDATE '.self::TB_USER_FILES.' f1 SET deleted=1,deleted_ts='.$time.',modify_ts='.$time." WHERE ".$where);
		}
	}


	/**
	 * 获取文件大小
	 * @param $uid
	 * @param $ids
	 * @return null
	 */
	public function get_files_size($uid,$ids)
	{
		if(empty($ids) || empty($uid))
		{
			return null;
		}
		$this->db->where("uid",$uid);
		if(!is_array($ids))
		{
			$this->db->where("id",$ids);
		}
		else if(is_array($ids) && count($ids)==1)
		{
			$this->db->where("id",$ids[0]);
		}
		else
		{
			$this->db->where_in("id",$ids);
		}
		$ret =  $this->db->select_sum("size","size")->get(self::TB_USER_FILES)->row_array();
		if(!empty($ret))
		{
			return (int)$ret['size'];
		}
		else
		{
			return 0;
		}
	}

	/**
	 * 移动文件位置
	 * @param $uid 用户id
	 * @param $ids 文件列表 如果是字符串是则修改一个，如果是数组时修改多个
	 * @param int $to 目标文件夹id 0则为根目录
	 * @return bool
	 */
	public function move_files($uid,$ids,$to=0)
	{
		if(empty($uid) || empty($ids))
		{
			return false;
		}
		$this->db->where("uid",$uid);
		if(!is_array($ids))
		{
			$this->db->where("id",$ids);
		}
		else if(is_array($ids) && count($ids)==1)
		{
			$this->db->where("id",$ids[0]);
		}
		else
		{
			$this->db->where_in("id",$ids);
		}
		return $this->db->update(self::TB_USER_FILES,array("folder_id"=>$to));

	}

	/**
	 * 检测文件的权限
	 * @param $uid 用户的id
	 * @param array $files 文件id组
	 * @param array $folders 文件夹id组
	 */
	public function check_own_files($uid, $files=array(), $folders=array()) {
		if (empty($uid) || (empty($files) && empty($folders))) {
			return;
		}

		$where = array(
			'uid' => $uid
		);
		$filter_file_ids = array();
		if (! empty($files)) {
			$filter_files = $this->db->select('id')
				->where($where)
				->where_in('id', $files)
				->get(self::TB_USER_FILES)
				->result_array();

			$filter_file_ids = array_column($filter_files, 'id');
		}

		$filter_folder_ids = array();
		if (! empty($folders)) {
			$filter_folders = $this->db->select('id')
				->where($where)
				->where_in('id', $folders)
				->get(self::TB_USER_FOLDERS)
				->result_array();

			$filter_folder_ids = array_column($filter_folders, 'id');
		}

		return array('files' => $filter_file_ids, 'folders' => $filter_folder_ids);
	}

	/**
	 * 搜索
	 * @param $uid
	 * @param string $keyword
	 * @param int $page
	 * @param int $total
	 * @param string $field
	 */
	public function search($uid, $keyword='', $page=0, $total=0, $field='*') {
		if (empty($uid) || $keyword === '') {
			return;
		}

		$where = array(
			'uid' 		=> $uid,
			'deleted' 	=> 0
		);

		$page  = (int)$page;
		$total = (int)$total;
		if ($page >= 0 && $total > 0) {
			$this->db->limit($total, $page * $total);
		}

		$result = $this->db->select($field)
					->from(self::TB_FILE)
					->where($where)
					->like('name', $keyword)
					->order_by("creation_ts", "desc")
					->get()
					->result_array();

		return $result;
	}
}